package com.test.exception;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 作用：controllerAdvice是SPringMVC提供异常处理机制：
 * 捕获所有项目模块controller产生的异常信息，将异常信息做定制给前端返回结果
 */
@RestControllerAdvice
//@ControllerAdvice
@ResponseBody
public class BasicExceptionHandler{

    //处理对应的异常类型：RuntimeException  ,没有封装完成的,指定状态码的异常信息
   /* @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> error(RuntimeException e){
        return ResponseEntity.status(400).body(e.getMessage());
    }*/

    /**
     * 处理其他自定义异常
     * 最后改良：将返回数据String改为自定义的ExceptionResult
     */
    @ExceptionHandler(MyException.class)
    public ResponseEntity<ExceptionResult> error(MyException e){
        System.out.println("异常 ----->>>>>" +  ResponseEntity.status(e.getStatus()).body(new ExceptionResult(e)));
        return ResponseEntity.status(e.getStatus()).body(new ExceptionResult(e));

    }

    @ExceptionHandler(IllegalStateException.class)
    public Map<String, String> result() {
        HashMap<String, String> map = new HashMap<>();
        map.put("status", "400");
        map.put("message", "用户已经退出");
        return map;
    }
}